<template>
  <div class="container">
    <headerBar :title="local.addSaleOrder" @changeLan="changeLan" @pageReturn="pageReturn"></headerBar>
    <div class="all" :style="{paddingTop: pdt+'px'}">
      <div class="stock-detail-panel">
        <div class="jt_flex jt_flex_dr mb_6">
          <span
            class="jt_flex form_label jt_flex_der name"
            style="justify-content: flex-end;"
            :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
          >
            <span style="color: red;">*</span>
            {{local.salesOrderNo}}：
          </span>
          <div class="jt_flex jt_flex_der w_calc_70 form_input bt_1">
            <input disabled :placeholder="local.automaticallygeneratedbythesystem" />
          </div>
        </div>
        <div class="jt_flex jt_flex_dr mt_mb_6">
          <span
            class="jt_flex form_label jt_flex_der"
            :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            style="justify-content:flex-end;"
          >{{local.businessDate}}：</span>
          <div class="jt_flex jt_flex_der form_input">
            <div class="btn">{{timeFormat}}</div>
          </div>
        </div>
        <div class="jt_flex jt_flex_dr mt_6">
          <span
            class="jt_flex form_label jt_flex_der"
            :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            style="justify-content: flex-end;"
          >{{local.orderStatus}}：</span>
          <div class="jt_flex jt_flex_der form_input">
            <span class="btn">{{local.notSaved}}</span>
          </div>
        </div>
      </div>
      <div class="top">
        <div class="stock-detail-panel">
          <div class="jt_flex jt_flex_dr">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >
              <span style="color: red;">*</span>
              {{local.customer}}：
            </div>
            <div class="jt_flex jt_flex_der w_calc_70 form_input bt_1">
              <block v-if="array.length == 0">
                <div>{{local.empty}}</div>
              </block>
              <block v-else>
                <picker
                  class
                  style="width: 100%"
                  @change="PickerChange"
                  :value="indexPicker"
                  :range="array"
                  :range-key="'customerName'"
                >
                  <input
                    type="default"
                    class="jt_flex"
                    v-model="customerName"
                    disabled
                    :placeholder="local.choose"
                  />
                  <!--  -->
                </picker>
                <span class="unit jt_flex">▼</span>
              </block>
            </div>
          </div>
        </div>
      </div>
      <div class="top">
        <div class="stock-detail-panel">
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_120'"
            >{{local.logisticsOrderNo}}：</div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex: 1;border-bottom: 2rpx solid #000;"
            >
              <block v-if="codeArray.length == 0">
                <div>{{local.empty}}</div>
              </block>
              <block v-else>
                <picker
                  class="weui-btn"
                  @change="PickerCodeChange"
                  :value="indexCodePicker"
                  :range="codeArray"
                  :range-key="'trackNumber'"
                  style="flex:1;"
                >
                  <input type="default" v-model="trackNumber" disabled :placeholder="local.choose" />
                </picker>
                <span class="unit">▼</span>
              </block>
            </div>
          </div>
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_120'"
            >
              <span style="color: red;">*</span>
              {{local.salesInvoiceNo}}：
            </div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex:1;border-bottom: 2rpx solid #000;"
            >
              <input v-model="saleOrderInvoice" :placeholder="local.peleaseEnter" />
            </div>
          </div>
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.invoiceDate}}：</div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex:1;border-bottom: 2rpx solid #000;"
            >
              <picker
                class="weui-btn"
                mode="date"
                :value="invoiceDate"
                start="1999-01-01"
                end="2099-01-01"
                @change="TimeChange"
              >
                <input v-model="invoiceDateFormat" :placeholder="local.peleaseEnter" disabled />
              </picker>
            </div>
          </div>
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_120'"
            >{{local.totalPrice}}：</div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex:1;border-bottom: 2rpx solid #000;"
            >
              <input v-model="totalPrice" :placeholder="local.peleaseEnter" />
            </div>
          </div>
          <div class="jt_flex jt_flex_dr mb_10">
            <div
              class="jt_flex form_label jt_flex_der jt_flex_row_right name"
              :class="lang == 'zh'||lang =='zh_CN'?'w_85':'w_110'"
            >{{local.paymentStatus}}：</div>
            <div
              class="jt_flex jt_flex_der form_input"
              style="flex:1;border-bottom: 2rpx solid #000;"
            >
              <picker
                class="weui-btn"
                :value="indexPayment"
                :range="paymentStatusList"
                :range-key="'dictLabel'"
                @change="paymentStatusChange"
              >
                <input v-model="paymentStatusLabel" :placeholder="local.choose" disabled />
              </picker>
            </div>
          </div>
        </div>
      </div>
      <!-- 选中的商品 -->
      <block v-if="selectGoodsList.length == 0">
        <div></div>
      </block>
      <block v-else>
        <div v-for="(item, i) in selectGoodsList" :key="i">
          <div class="select-panel">
            <div class="opreate jt_flex jt_flex_row_right">
              <div
                class="open"
                @click="openOrClose(selectGoodsList,i)"
              >{{item.open ? local.fold : local.unfold}}</div>
              <div class="detele-text" @click="deleteRow(selectGoodsList,i)">{{local.deletesingle}}</div>
            </div>
            <div class="panel-goods">
              <div
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.goodsName}}：</div>
              <div class="names-goods">{{item.goodsName}}</div>
            </div>
            <div class="panel-goods">
              <div
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.buyArea}}：</div>
              <div class="names-goods">{{item.buyAreaName || ''}}</div>
            </div>
            
            <div class="panel-goods">
              <div
                class="name"
                :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
              >{{local.warehouseOut}}：</div>
              <div class="names-goods">{{item.warehouseName}}</div>
            </div>
          </div>
          <block v-if="item.open">
            <div class="select-photo">
              <div class="a">{{local.photosBeforeAcceptance}}</div>
              <div class="b">
                <div class="page">
                  <div class="weui-uploader__bd">
                    <div class="weui-uploader__files" id="uploaderFiles">
                      <block v-if="item.beginPicUrl == null">
                        <div>{{local.empty}}</div>
                      </block>
                      <block v-else>
                        <block v-for="(ite, index) in item.beginPicUrlList" :key="index">
                          <div
                            class="weui-uploader__file"
                            @click="predivImageBegin"
                            :data-urls="item.beginPicUrlList"
                            :id="ite"
                          >
                            <img class="weui-uploader__img" :src="Shop+ite" mode="aspectFill" />
                          </div>
                        </block>
                      </block>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="stock-detail-panel">
              <div class="jt_flex jt_flex_dr">
                <div
                  class="jt_flex form_label jt_flex_der jt_flex_row_right"
                  :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
                >{{local.grade}}：</div>
                <div class="jt_flex jt_flex_der form_input">{{item.goodsLevelName}}</div>
              </div>
              <div class="jt_flex jt_flex_dr">
                <div
                  class="jt_flex form_label jt_flex_der jt_flex_row_right"
                  :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
                >{{local.beltType}}：</div>
                <div class="jt_flex jt_flex_der form_input">{{item.beltTypeName}}</div>
              </div>
            </div>
            <div class="stock-detail-panel">
              <div class="jt_flex jt_flex_dr">
                <span
                  class="jt_flex form_label jt_flex_der jt_flex_row_right"
                  :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
                >{{local.thickness}}：</span>
                <div class="jt_flex jt_flex_der form_input w_calc_70 bt_1 pd_t_10 mb_1">
                  <input placeholder="请输入厚度" disabled v-model="item.sizeHeight" />
                  <span class="unit">MM</span>
                </div>
              </div>
              <div class="jt_flex jt_flex_dr">
                <span
                  class="jt_flex form_label jt_flex_der jt_flex_row_right"
                  :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
                >{{local.width}}：</span>
                <div class="jt_flex jt_flex_der form_input w_calc_70 bt_1 pd_t_10 mb_10">
                  <input placeholder="请输入宽度" disabled v-model="item.sizeWidth" />
                  <span class="unit">MM</span>
                </div>
              </div>
              <div class="jt_flex jt_flex_dr">
                <span
                  class="jt_flex form_label jt_flex_der jt_flex_row_right"
                  :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
                >{{local.length}}：</span>
                <div class="jt_flex jt_flex_der form_input w_calc_70 bt_1 pd_t_10 mb_10">
                  <input placeholder="请输入长度" disabled v-model="item.sizeLong" />
                  <span class="unit">M</span>
                </div>
              </div>
              <div class="jt_flex jt_flex_dr">
                <span
                  class="jt_flex form_label jt_flex_der jt_flex_row_right"
                  :class="lang == 'zh'||lang =='zh_CN'?'w_70':'w_110'"
                >{{local.weight}}：</span>
                <div class="jt_flex jt_flex_der form_input w_calc_70 bt_1 pd_t_10 mb_10">
                  <input placeholder="请输入重量" disabled v-model="item.weight" />
                  <span class="unit">T</span>
                </div>
              </div>
            </div>
            <div class="select-photo">
              <div class="a">{{local.photosAfterAcceptance}}</div>
              <div class="b">
                <div class="page">
                  <div class="weui-uploader__bd">
                    <div class="weui-uploader__files" id="uploaderFiles">
                      <block v-if="item.endPicUrl == null">
                        <div>{{local.empty}}</div>
                      </block>
                      <block>
                        <block v-for="(ite, index) in item.endPicUrlList" :key="index">
                          <div
                            class="weui-uploader__file"
                            @click="predivImageEnd"
                            :id="ite"
                            :data-urls="item.endPicUrlList"
                          >
                            <img class="weui-uploader__img" :src="Shop+ite" mode="aspectFill" />
                          </div>
                        </block>
                      </block>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </block>
        </div>
      </block>
      <div
        class="add-btn"
        @click="routerToUrl('../../pages/selectGoods/index?page='+'sale')"
      >+ {{local.continueAdding}}</div>
      <div class="remark">
        <div>{{local.remark}}:</div>
        <textarea
          v-model="remark"
          style="height: 100rpx;max-width: 879rpx;resize: none;padding-left: 18rpx;"
        ></textarea>
      </div>
      <div class="bottom-bar">
        <div class="sum">{{local.added}}：{{goodsCount}}{{local.piece}}</div>
        <div class="save-draft" @click="confirm('save')">{{local.saveNew}}</div>
        <div class="confirm-btn" @click="confirm('submit')">{{local.confirm}}</div>
      </div>
    </div>
  </div>
</template>

<script>
import card from '@/components/card'
import home from '@/api/home'
import headerBar from '@/components/headerBar'
import { dictMatching, previewImage } from '@/utils/index'
import Shop from '../../../../config/shop'
import { throttle } from '@/utils/throttle'
var a
export default {
  components: {
    card,
    headerBar
  },
  onShow () {
    this.initLang()
    if (a) {
      a = false
      return
    } else {
      // 上一页返回的数据
      this.initMyData()
    }
  },
  onLoad () {
    this.initLang()
    var myDate = new Date()
    myDate.toLocaleDateString()
    this.time = myDate.toLocaleDateString() // 获取当前日期，展示
    this.getLogisicOrder() // 物流单号列表
    this.pdt = this.globalData.CustomBar // 导航
    this.initData()
  },
  computed:{
    timeFormat(){
      return wx.$timeFormat(this.time)
    },
    invoiceDateFormat(){
      return this.invoiceDate ? wx.$timeFormat(this.invoiceDate) : "" //new Date(this.invoiceDate).$format('dd/MM/yyyy') : ''
    }
  },
  methods: {
    deleteRow(list,index){
      let goodsList = wx.getStorageSync('selectGoodsIdList')
      let newList = goodsList.filter(item => item !== list[index].id)
      wx.setStorageSync('selectGoodsIdList',newList)
      list.splice(index,1)
      
    },
    openOrClose(list, index) {
      list[index].open = !list[index].open
      list.push()
    },
    TimeChange (e) {
      this.invoiceDate = e.mp.detail.value
    },
    paymentStatusChange(e){
      this.indexPayment = e.mp.detail.value
      this.paymentStatus = this.paymentStatusList[e.mp.detail.value].dictValue
      this.paymentStatusLabel = this.paymentStatusList[e.mp.detail.value].dictLabel
    },
    initLang(){
      this.local = wx.getStorageSync('local')
      this.lang = wx.getStorageSync('lang')
    },
    initData(){
      this.array = wx.getStorageSync('customerArray') || []
      this.resetData()
    },
    resetData(){
      this.trackNumber = ''
      this.saleOrderInvoice = ''
      this.goodsCount = 0
      this.selectGoodsList = []
      this.customerId = ''
      this.customerName = ''
      this.indexCodePicker = 0
      this.indexPicker = 0
      this.remark = ''
      this.totoalPrice = ''
      this.indexPicker = 0,
      this.paymentStatus = ''
      wx.setStorageSync('selectGoodsIdList',[])
    },
    initMyData(){
      var pages = getCurrentPages();
      var currPage = pages[pages.length - 1]; //当前页面
      let myData = currPage.data.mydata;
      this.mydata.selectGoodsItem = myData ? myData.selectGoodsItem : []
      if(myData){
        let item = this.mydata.selectGoodsItem
        item.logisticsGoods = 2 //选择的销售商品
        item.goodsLevelName = dictMatching(wx.getStorageSync('goodsLevel') || [],item.goodsLevel)
        item.beltTypeName = dictMatching(wx.getStorageSync('beltType') || [], item.beltType)
        item.beginPicUrlList = item.beginPicUrl == null ? []:item.beginPicUrl.split(',')
        item.endPicUrlList = item.endPicUrl == null ? []: item.endPicUrl.split(',')
        this.selectGoodsList.push(item)
        this.selectGoodsList = this.unique(this.selectGoodsList)
        this.goodsCount = this.selectGoodsList.length
      }
    },
    unique(arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
    },
    // 获取物流单号
    async getLogisicOrder () {
      const {rows, code, msg} = await home.getLogisicOrder({pageSize: this.pageSize, pageNum: this.pageNum, trackNumber: this.trackNumber})
      if(code == 0 ){
        this.codeArray = rows
      }else {
        wx.showToast({
          title: msg,
          icon: 'none',
          duration: 4000
        })
      }
    },
    pageReturn () {
      this.resetData()
      wx.setStorageSync('selectGoodsIdList', [])
    },
    changeLan (val,lang) {
      this.local = val
      this.lang = lang
    },
    async confirm (type) {
      if(this.customerName == ''){
        //保存和提交，客户必填
        wx.showToast({
          title: `${this.local.customer}${this.local.required}`,
          icon: 'none',
          duration: 2000
        })
        return
      }
      if(type == 'submit' && this.saleOrderInvoice == ''){
        wx.showToast({
          title: `${this.local.salesInvoiceNo}${this.local.required}`,
          icon: 'none',
          duration: 2000
        })
        return 
      }
      if(this.selectGoodsList.length == 0){
        //保存和提交，商品必选
        wx.showToast({
          title: this.local.addSaleOrderTip,
          icon: 'none',
          duration: 2000
        })
        return
      }
      let warehouseIds = []
      this.selectGoodsList.map(item => {
        warehouseIds.push(item.warehouseId)
      })
      this.weight = this.selectGoodsList.reduce((prev, next) =>{
        return prev + next.weight
      },0)
      this.warehouseId = [...new Set(warehouseIds)]
      wx.showLoading({
        title: type == 'submit' ? `${this.local.submitting}` : `${this.local.saving}`
      })
      this.gotoPage(`/packageA/pages/saleOrderList/index`,type)
    },
    gotoPage: throttle(
      0,
      false,
      function (url,type) {
        this._func(url,type)
      },
      false
    ),
     _func (url,type) {
       let submitType = type == 'submit' ? {submitType: this.submitType} : ''
      home.addSaleOrderList({
        weight: this.weight,
        trackNumber: this.trackNumber == this.local.empty ? '': this.trackNumber,
        ...submitType,
        customerId: this.customerId,
        warehouseId: this.warehouseId.join(),
        goodsCount: this.goodsCount,
        saleOrderInvoice: this.saleOrderInvoice,
        invoiceDate: this.invoiceDate,
        paymentStatus: this.indexPayment == null? '':this.paymentStatusList[this.indexPayment].dictValue,
        totalPrice: this.totalPrice == null ? '':this.totalPrice,
        remark: this.remark,
        goodList: JSON.stringify(this.selectGoodsList)}).then((data) => {
        wx.hideLoading()
        if (data.code !== 0) {
          wx.showToast({
            title: data.msg,
            duration: 2000,
            icon: 'none'
          })
          return
        }
        // 重置方法
        this.resetData()
        wx.navigateTo({
          url: url
        })
      }).catch((err) => {
        console.log('err', err)
      })
    },
    PickerCodeChange (e) {
      this.indexCodePicker = e.mp.detail.value
      this.trackNumber = this.codeArray[e.mp.detail.value].trackNumber
      //选择物流单号，过滤信息
      this.codeArray.map(item => {
        if(item.trackNumber == this.trackNumber && item.goodsList.length){
          item.goodsList.map(good => {
            this.selectGoodsList.push({
              ...good,
              goodsLevelName: dictMatching(wx.getStorageSync('goodsLevel') || [],good.goodsLevel),
              beltTypeName: dictMatching(wx.getStorageSync('beltType') || [], good.beltType),
              beginPicUrlList: good.beginPicUrl == null ? []: good.beginPicUrl.split(),
              endPicUrlList: good.endPicUrl == null ? []: good.endPicUrl.split(),
              logisticsGoods: 1 //物流商品
            })
          })
          // this.selectGoodsList = item.goodsList
        }else {
          this.selectGoodsList = []
        }
      })
    },
    PickerChange (e) {
      this.indexPicker = e.mp.detail.value
      this.customerId = this.array[e.mp.detail.value].customerId
      this.customerName = this.array[e.mp.detail.value].customerName
    },
    routerToUrl (url) {
      wx.navigateTo({
        url
      })
    },
    chooseImage (e) {
      var _this = this
      wx.chooseImage({
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          _this.files = _this.files.concat(res.tempFilePaths)
        }
      })
    },
    predivImageBegin (e) {
      a = true
      previewImage(e)
    },
    predivImageEnd (e) {
      a = true
      previewImage(e)
    }
  },
  data () {
    return {
      invoiceDate: '',
      lang: wx.getStorageSync('lang'),
      Shop: Shop.BASE_URL,
      logisicOrderList: [],
      selectGoodsList: [],
      mydata: {
        selectGoodsItem: {}
      },
      arrayBelt: [],
      arrayLevel: [],
      objSave: [],
      time: '',
      weight: 0,
      trackNumber: '',
      indexCodePicker: 0,
      codeArray: [],
      remark: '',
      saleOrderInvoice: '',
      pdt: 66,
      local: wx.getStorageSync('local'),
      obj: [], // 放在缓存中的商品信息
      goodsId: [], // 可多个
      warehouseId: [], // 可多个
      customerId: '140',
      customerName: '',
      goodsCount: 0,
      submitType: 1, // 保存新增不用传,确定提交传1
      files: [],
      indexPicker: 0,
      array: ['美国', '中国', '巴西', '日本'],
      logs: [],
      fileList: [],
      pageNum: 1,
      pageSize: 200,
      indexPayment: null,
      paymentStatus: '',
      paymentStatusLabel: '',
      paymentStatusList: wx.getStorageSync('paymentStatus') 
    }
  },
  created () {
  }
}
</script>

<style scoped lang="scss">
@import 'index';
.log-list {
  display: flex;
  flex-direction: column;
  padding: 40rpx;
}

.log-item {
  margin: 10rpx;
}
</style>
